<template>
    <div class="department-manage">
        <!-- 面包屑和标题 -->
        <el-breadcrumb separator="/" class="mb-2">
            <el-breadcrumb-item>系统管理</el-breadcrumb-item>
            <el-breadcrumb-item>系统基础管理</el-breadcrumb-item>
            <el-breadcrumb-item>组织管理</el-breadcrumb-item>
        </el-breadcrumb>
        <div class="page-title">组织管理</div>

        <!-- 查询区 -->
        <div class="search-area">
            <el-input v-model="query.departmentName" placeholder="部门名称" clearable style="width: 220px;" />
            <el-button type="primary" @click="onSearch">查询</el-button>
            <el-button @click="onReset">重置</el-button>
            <el-button type="danger" @click="onBatchDelete" :disabled="!selected.length" class="ml-2">批量删除</el-button>
            <el-button type="primary" class="new-dept-btn" @click="onCreateDepartment">新建部门</el-button>
        </div>

        <!-- 部门表格 -->
        <el-table :data="tableData" border stripe style="width: 100%" @selection-change="onSelectionChange">
            <el-table-column type="selection" width="40" />
            <el-table-column prop="DepartmentName" label="部门名称" width="150" />
            <el-table-column prop="ParentDeptName" label="上级部门" width="150">
                <template #default="scope">
                    {{ scope.row.ParentDeptName || '无上级部门' }}
                </template>
            </el-table-column>
            <el-table-column prop="Status" label="状态" width="100">
                <template #default="scope">
                    <div class="status-tag">
                        <span v-if="scope.row.Status" class="dot enabled"></span>
                        <span v-else class="dot disabled"></span>
                        {{ scope.row.Status ? '启用' : '禁用' }}
                    </div>
                </template>
            </el-table-column>
            <el-table-column prop="MemberCount" label="成员数量" width="100" />
            <el-table-column prop="Description" label="部门描述" min-width="180" />
            <el-table-column prop="ManagerId" label="管理者" width="100">
                <template #default="scope">
                    {{ getManagerName(scope.row.ManagerId) }}
                </template>
            </el-table-column>
            <el-table-column label="排序" width="70">
                <template #default="scope">
                    {{ scope.$index + 1 }}
                </template>
            </el-table-column>
            <el-table-column label="操作" width="220">
                <template #default="scope">
                    <div class="operation-buttons">
                        <el-button type="primary" plain size="small" @click="onEdit(scope.row)">编辑</el-button>
                        <el-button type="primary" plain size="small" @click="onSetStatus(scope.row)">设置状态</el-button>
                        <el-button type="danger" plain size="small" @click="onDelete(scope.row)">删除</el-button>
                    </div>
                </template>
            </el-table-column>
        </el-table>

        <!-- 分页 -->
        <CustomPagination class="mt-2" :currentPage="pageIndex" :pageSize="pageSize" :totalCount="pageInfo.totalCount"
            :totalPage="pageInfo.totalPage" @size-change="onPageSizeChange" @current-change="onCurrentPageChange" />

        <!-- 新建/编辑部门弹窗 -->
        <el-dialog v-model="departmentDialog.visible" :title="departmentDialog.isEdit ? '编辑部门' : '新建部门'" width="500px">
            <el-form :model="departmentForm" label-width="90px" :rules="departmentRules" ref="departmentFormRef"
                class="department-form">
                <el-form-item label="部门名称:" prop="departmentName" required>
                    <el-input v-model="departmentForm.departmentName" placeholder="请输入部门名称" />
                </el-form-item>
                <el-form-item label="上级部门:" prop="parentId">
                    <DepartmentTreeSelect v-model="departmentForm.parentId" placeholder="请选择上级部门" />
                </el-form-item>
                <el-form-item label="主管人员:" prop="managerId" required>
                    <UserSelector v-model="departmentForm.managerId" placeholder="请选择主管人员" />
                </el-form-item>
                <el-form-item label="描述:" prop="description">
                    <el-input v-model="departmentForm.description" type="textarea" :rows="4" placeholder="请输入部门描述"
                        maxlength="100" show-word-limit />
                </el-form-item>
            </el-form>
            <template #footer>
                <div class="dialog-footer">
                    <el-button @click="departmentDialog.visible = false">取消</el-button>
                    <el-button type="primary" @click="onSaveDepartment">保存</el-button>
                </div>
            </template>
        </el-dialog>
    </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import {
    getDepartmentList,
    addDepartment,
    updateDepartment,
    deleteDepartment,
    setDepartmentStatus,
    type DepartmentListParams,
    type DepartmentItem,
    type DepartmentListData,
    type AddDepartmentParams,
    type UpdateDepartmentParams,
    type SetDepartmentStatusParams
} from '@/api/department'
import { ElMessage, ElMessageBox } from 'element-plus'
import CustomPagination from '@/components/CustomPagination.vue'
import UserSelector from '@/components/UserSelector.vue'
import DepartmentTreeSelect from '@/components/DepartmentTreeSelect.vue'

// 自定义API响应类型
interface ApiResponse<T = any> {
    IsSuc: boolean;
    Msg: string;
    Data: T;
    Code?: number;
}

// 查询参数
const query = reactive({
    departmentName: ''
})

// 分页参数
const pageIndex = ref(1)
const pageSize = ref(10)
const pageInfo = reactive({
    totalCount: 0,
    totalPage: 0
})

// 表格数据
const tableData = ref<DepartmentItem[]>([])
// 多选选中的部门
const selected = ref<DepartmentItem[]>([])

// 部门表单
const departmentFormRef = ref()
interface DepartmentForm {
    id: string;
    departmentName: string;
    managerId: number | null;
    parentId: number;
    description: string;
}

const departmentForm = reactive<DepartmentForm>({
    id: '',
    departmentName: '',
    managerId: null,
    parentId: 0,
    description: ''
})

// 部门表单校验规则
const departmentRules = {
    departmentName: [
        { required: true, message: '请输入部门名称', trigger: 'blur' },
        { min: 2, max: 50, message: '部门名称长度应在2-50个字符之间', trigger: 'blur' }
    ],
    managerId: [
        { required: true, message: '请选择主管人员', trigger: 'change' }
    ],
    description: [
        { max: 100, message: '描述不能超过100个字符', trigger: 'blur' },
        {
            validator: (rule: any, value: string, callback: any) => {
                if (value && value.trim() === '') {
                    callback(new Error('描述不能只包含空格'));
                } else {
                    callback();
                }
            },
            trigger: 'blur'
        }
    ]
}

// 部门对话框状态
const departmentDialog = reactive({
    visible: false,
    isEdit: false
})

// 获取部门列表
const fetchDepartmentList = async () => {
    try {
        const params: DepartmentListParams = {
            DepartmentName: query.departmentName || "",
            pageIndex: pageIndex.value,
            pageSize: pageSize.value
        }

        const response = await getDepartmentList(params) as unknown as ApiResponse;
        console.log('获取部门列表响应:', response);

        if (response.IsSuc && response.Data) {
            const responseData = response.Data as DepartmentListData;

            // 创建部门ID到部门名称的映射
            const deptNameMap: Record<number, string> = {};
            responseData.Data.forEach(dept => {
                deptNameMap[dept.DeptId] = dept.DepartmentName;
            });

            tableData.value = responseData.Data.map(dept => ({
                ...dept, // 保留所有原始字段
                id: dept.DeptId.toString(), // 兼容现有组件的id字段
                ParentDeptName: dept.ParentId ? deptNameMap[dept.ParentId] || `未知部门(ID:${dept.ParentId})` : '无上级部门'
            }));

            pageInfo.totalCount = responseData.TotalCount;
            pageInfo.totalPage = responseData.TotalPage;
        } else {
            ElMessage.error(response.Msg || '获取部门列表失败');
            tableData.value = [];
            pageInfo.totalCount = 0;
            pageInfo.totalPage = 0;
        }
    } catch (error: any) {
        console.error('获取部门列表失败:', error);
        ElMessage.error(error.message || '获取部门列表失败');
        tableData.value = [];
        pageInfo.totalCount = 0;
        pageInfo.totalPage = 0;
    }
}

// 查询按钮点击事件
const onSearch = () => {
    pageIndex.value = 1
    fetchDepartmentList()
}

// 重置按钮点击事件
const onReset = () => {
    query.departmentName = ''
    pageIndex.value = 1
    fetchDepartmentList()
}

// 多选变化事件
const onSelectionChange = (rows: any[]) => {
    selected.value = rows
}

// 分页大小变化事件
const onPageSizeChange = (newSize: number) => {
    pageSize.value = newSize
    pageIndex.value = 1
    fetchDepartmentList()
}

// 当前页变化事件
const onCurrentPageChange = (newPage: number) => {
    pageIndex.value = newPage
    fetchDepartmentList()
}

// 新建部门按钮点击事件
const onCreateDepartment = () => {
    departmentDialog.isEdit = false
    resetDepartmentForm()
    departmentDialog.visible = true
}

// 编辑部门按钮点击事件
const onEdit = (row: any) => {
    departmentDialog.isEdit = true
    // 先清空表单，防止显示上次编辑的数据
    resetDepartmentForm()

    // 设置表单数据
    departmentForm.id = row.DeptId.toString()
    departmentForm.departmentName = row.DepartmentName
    departmentForm.managerId = row.ManagerId || null
    departmentForm.parentId = row.ParentId || 0
    departmentForm.description = row.Description || ''

    // 显示对话框
    departmentDialog.visible = true

    // 确保下一个渲染周期后表单数据已更新
    setTimeout(() => {
        if (departmentFormRef.value) {
            departmentFormRef.value.clearValidate()
        }
    }, 0)
}

// 重置部门表单
const resetDepartmentForm = () => {
    departmentForm.id = ''
    departmentForm.departmentName = ''
    departmentForm.managerId = null
    departmentForm.parentId = 0
    departmentForm.description = ''
}

// 保存部门按钮点击事件
const onSaveDepartment = async () => {
    departmentFormRef.value?.validate(async (valid: boolean) => {
        if (!valid) return

        try {
            if (departmentDialog.isEdit) {
                // 编辑现有部门
                const updateParams: UpdateDepartmentParams = {
                    DeptId: parseInt(departmentForm.id),
                    DepartmentName: departmentForm.departmentName,
                    ManagerId: departmentForm.managerId || 0,
                    Description: departmentForm.description,
                    ParentId: departmentForm.parentId
                }

                const response = await updateDepartment(updateParams) as unknown as ApiResponse;
                console.log('更新部门响应:', response);
                ElMessage.success('部门更新成功');
                departmentDialog.visible = false;
                fetchDepartmentList();
            } else {
                // 创建新部门
                const addParams: AddDepartmentParams = {
                    DepartmentName: departmentForm.departmentName,
                    ManagerId: departmentForm.managerId || 0,
                    Description: departmentForm.description,
                    ParentId: departmentForm.parentId
                }

                const response = await addDepartment(addParams) as unknown as ApiResponse;
                console.log('添加部门响应:', response);
                ElMessage.success('部门创建成功');
                departmentDialog.visible = false;
                fetchDepartmentList();
            }
        } catch (error: any) {
            console.error('保存部门失败:', error);
            ElMessage.error(error.message || '保存部门失败');
        }
    })
}

// 删除部门按钮点击事件
const onDelete = (row: any) => {
    ElMessageBox.confirm(`确定要删除部门"${row.DepartmentName}"吗？`, '删除确认', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
    }).then(async () => {
        try {
            // 调用删除部门API，传入deptId参数
            const response = await deleteDepartment(row.DeptId) as unknown as ApiResponse;
            console.log('删除部门响应:', response);

            ElMessage.success('删除成功');
            fetchDepartmentList(); // 刷新列表
        } catch (error: any) {
            console.error('删除部门失败:', error);
            ElMessage.error(error.message || '删除部门失败');
        }
    }).catch(() => {
        // 用户取消删除，不做任何操作
    })
}

// 设置部门状态按钮点击事件
const onSetStatus = (row: any) => {
    // 计算要设置的新状态 (取反当前状态)
    const newStatus = !row.Status

    ElMessageBox.confirm(
        `确定要${newStatus ? '启用' : '禁用'}部门"${row.DepartmentName}"吗？`,
        `${newStatus ? '启用' : '禁用'}确认`,
        {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
        }
    ).then(async () => {
        try {
            // 调用设置状态API
            const params: SetDepartmentStatusParams = {
                DeptId: row.DeptId,
                Status: newStatus
            }
            const response = await setDepartmentStatus(params) as unknown as ApiResponse;
            console.log('设置部门状态响应:', response);

            ElMessage.success(`${newStatus ? '启用' : '禁用'}成功`);
            fetchDepartmentList(); // 刷新列表
        } catch (error: any) {
            console.error('设置部门状态失败:', error);
            ElMessage.error(error.message || '设置部门状态失败');
        }
    }).catch(() => {
        // 用户取消操作，不做任何处理
    })
}

// 批量删除按钮点击事件
const onBatchDelete = () => {
    if (selected.value.length === 0) {
        ElMessage.warning('请选择要删除的部门');
        return;
    }

    // 过滤掉有成员的部门
    const canDeleteDepts = selected.value.filter((dept: DepartmentItem) => dept.MemberCount === 0);

    if (canDeleteDepts.length === 0) {
        ElMessage.warning('选中的部门都有成员，无法删除');
        return;
    }

    const deptNames = canDeleteDepts.map(dept => dept.DepartmentName).join('、');
    ElMessageBox.confirm(`确定要删除选中的部门 ${deptNames} 吗？`, '批量删除确认', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
    }).then(async () => {
        try {
            let successCount = 0;
            const errors: string[] = [];

            // 逐个删除选中的部门
            for (const dept of canDeleteDepts) {
                try {
                    const response = await deleteDepartment(dept.DeptId) as unknown as ApiResponse;
                    if (response.IsSuc) {
                        successCount++;
                    } else {
                        errors.push(`${dept.DepartmentName}: ${response.Msg || '未知错误'}`);
                    }
                } catch (err: any) {
                    errors.push(`${dept.DepartmentName}: ${err.message || '未知错误'}`);
                }
            }

            if (successCount > 0) {
                ElMessage.success(`成功删除 ${successCount} 个部门`);
            }

            if (errors.length > 0) {
                ElMessage.error(`删除失败的部门: ${errors.join('; ')}`);
            }

            fetchDepartmentList(); // 刷新列表
        } catch (error: any) {
            console.error('批量删除部门失败:', error);
            ElMessage.error(error.message || '批量删除部门失败');
        }
    }).catch(() => {
        // 用户取消批量删除，不做任何操作
    });
}

// 根据ID获取管理者名称
const getManagerName = (managerId: number | null): string => {
    // 如果managerId为null或0，显示未指定
    if (managerId === null || managerId === 0) {
        return '未指定管理者';
    }

    // 根据ID映射到真实姓名
    const managerNameMap: Record<number, string> = {
        2: '超级管理员',
        3: '孙璐',
        4: '杜安琪',
        5: '张秀英',
        6: '蔡诗涵'
    };

    // 如果找到对应的名称则返回，否则返回ID
    return managerNameMap[managerId] || `ID: ${managerId}`;
}

// 页面加载时获取数据
onMounted(() => {
    fetchDepartmentList()
})
</script>

<style scoped>
.department-manage {
    background: #fff;
    border-radius: 8px;
    padding: 18px;
    min-height: 600px;
    box-shadow: 0 2px 8px 0 rgba(0, 0, 0, 0.03);
}

.page-title {
    font-size: 20px;
    font-weight: bold;
    margin-bottom: 18px;
}

.search-area {
    display: flex;
    align-items: center;
    margin-bottom: 16px;
    gap: 10px;
}

.search-area .new-dept-btn {
    margin-left: auto;
}

.status-tag {
    display: flex;
    align-items: center;
}

.dot {
    display: inline-block;
    width: 8px;
    height: 8px;
    border-radius: 50%;
    margin-right: 5px;
}

.dot.enabled {
    background-color: #67C23A;
}

.dot.disabled {
    background-color: #F56C6C;
}

.mt-2 {
    margin-top: 18px;
}

.mb-2 {
    margin-bottom: 18px;
}

.ml-2 {
    margin-left: 8px;
}

.pagination-container {
    display: flex;
    justify-content: flex-end;
    margin-top: 16px;
}

.operation-buttons {
    display: flex;
    gap: 5px;
    flex-wrap: nowrap;
}

.operation-buttons .el-button {
    padding: 5px 8px;
    font-size: 12px;
}

.department-form .el-form-item {
    margin-bottom: 20px;
}

.dialog-footer {
    display: flex;
    justify-content: flex-end;
    gap: 10px;
}
</style>